package com.example.take_out_admin.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.take_out_admin.common.Result;
import com.example.take_out_admin.common.lang.constant.StatusConstant;
import com.example.take_out_admin.common.lang.dto.EmployeeDto;
import com.example.take_out_admin.config.JwtConfig;
import com.example.take_out_admin.entity.Employee;
import com.example.take_out_admin.exceptions.BusinessException;
import com.example.take_out_admin.exceptions.enumetation.ResponseEnum;
import com.example.take_out_admin.mapper.EmployeeMapper;
import com.example.take_out_admin.service.EmployeeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.take_out_admin.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import jakarta.servlet.http.HttpServletRequest;

/**
 * <p>
 * 员工信息 服务实现类
 * </p>
 *
 * @author FZ
 * @since 2024-06-29
 */
@Slf4j
@Service
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements EmployeeService {

    @Resource
    private EmployeeMapper employeeMapper;

    @Resource
    private JwtConfig jwtConfig;

    @Resource
    private HttpServletRequest request;

    @Override
    public Result login(EmployeeDto employeeDto) {
        LambdaQueryWrapper<Employee> wrapper = new LambdaQueryWrapper<Employee>()
                .eq(Employee::getUsername, employeeDto.getUsername());
        Employee employee = employeeMapper.selectOne(wrapper);

        if (employee == null) {
            log.info("用户名{}不存在", employeeDto.getUsername());
            throw new BusinessException(ResponseEnum.INVALID_ACCOUNT);
        }

        String password = DigestUtils.md5DigestAsHex(employeeDto.getPassword().getBytes());
        if (!employee.getPassword().equals(password)) {
            log.info("用户名{} 密码{}错误", employeeDto.getUsername(), employeeDto.getPassword());
            throw new BusinessException(ResponseEnum.INVALID_ACCOUNT);
        }

        // 签发token
        String token = JwtUtils.createJwt(
                employee.getId(),
                employee.getUsername(),
                "",
                jwtConfig.getTtl(),
                jwtConfig.getKey()
        );

        log.info("token: {}", token);

        return Result.success(token);
    }

    @Override
    public void updateEmployee(Employee employee) {
        // TODO: 封装该方法(鉴权的部分) 通过Filter?拦截
        String token = request.getHeader("Authorization");
        log.info("token:{}",token);
        if(token==null) {
            throw new BusinessException(ResponseEnum.TOKEN_ERROR);
        }
        if(!JwtUtils.validateToken(token,jwtConfig.getKey())){
            throw new BusinessException(ResponseEnum.TOKEN_EXPIRED);
        }

        Claims claims = JwtUtils.parseJwt(token, jwtConfig.getKey());
        String name = claims.get("name", String.class);

        employee.setUpdateUser(name);

    }

    @Override
    public String parseJwt(String token) {
        Claims claims = JwtUtils.parseJwt(token, jwtConfig.getKey());
        String name = claims.get("name", String.class);
        return name;//JSONUtil.toJsonStr(claims);
    }

    @Override
    public void saveEmployee(Employee employee) {
        String token = request.getHeader("Authorization");
        log.info("token:{}",token);
        if(token==null) {
            throw new BusinessException(ResponseEnum.TOKEN_ERROR);
        }
        if(!JwtUtils.validateToken(token,jwtConfig.getKey())){
            throw new BusinessException(ResponseEnum.TOKEN_EXPIRED);
        }

        Claims claims = JwtUtils.parseJwt(token, jwtConfig.getKey());
        String name = claims.get("name", String.class);

        employee.setCreateUser(name);
        employee.setUpdateUser(name);

        String encryptedPassword = DigestUtils.md5DigestAsHex(employee.getPassword().getBytes());
        employee.setPassword(encryptedPassword);

        this.save(employee);
    }

    /**
     * 启用/禁用用户
     * @param status
     * @param id
     */
    @Override
    public void startOrStop(Integer status, String id) {
        Employee employee = employeeMapper.selectById(id);
        if(employee.getStatus().equals(StatusConstant.ENABLE)){
            //禁用员工
            employee.setStatus(StatusConstant.DISABLE);
            employeeMapper.updateById(employee);
            return;
        }
        //启用员工
        employee.setStatus(StatusConstant.ENABLE);
        employeeMapper.updateById(employee);
    }

    @Override
    public boolean validateToken(String token) {
        return JwtUtils.validateToken(token, jwtConfig.getKey());
    }
}
